package com.tamo.ppresta.base;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;

import com.hjq.http.EasyConfig;
import com.hjq.http.config.IRequestInterceptor;
import com.hjq.http.config.IRequestServer;
import com.hjq.http.model.HttpHeaders;
import com.hjq.http.model.HttpParams;
import com.hjq.http.request.HttpRequest;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.tamo.ppresta.BuildConfig;
import com.tamo.ppresta.constant.NET_CONSTANT;
import com.tamo.ppresta.db.DaoMaster;
import com.tamo.ppresta.greendao.DBManager;
import com.tamo.ppresta.http.ReleaseServer;
import com.tamo.ppresta.http.RequestHandler;
import com.tamo.ppresta.http.TestServer;
import com.tencent.mmkv.MMKV;

import org.greenrobot.greendao.database.Database;

import okhttp3.OkHttpClient;


/**
 * @author yeyang
 * @name ppresta
 * @class name：com.tamo.ppresta.base
 * @class describe
 * @time 2022/12/18 14:46
 * @change
 * @chang time
 * @class describe
 */
public class BaseApplication extends Application {
    //单例模式
    private static BaseApplication baseApplication = null;
    public boolean isDebug;
    private OkHttpClient okHttpClient;

    @Override
    public void onCreate() {
        super.onCreate();
        baseApplication = this;
        initNetWork();
        initGreenDao();
    }

    private void initGreenDao(){
        DBManager.getInstance(getApplicationContext());
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(android.R.color.holo_blue_bright, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    public static BaseApplication getInstance() {
        return baseApplication;
    }

    public void initNetWork() {
        MMKV.initialize(this);
        // 网络请求框架初始化
        IRequestServer server;
        if (BuildConfig.DEBUG) {
            server = new TestServer();
        } else {
            server = new ReleaseServer();
        }

        okHttpClient = new OkHttpClient.Builder()
                .build();

        EasyConfig.with(okHttpClient)
                // 是否打印日志
                //.setLogEnabled(BuildConfig.DEBUG)
                // 设置服务器配置（必须设置）
                .setServer(server)
                // 设置请求处理策略（必须设置）
                .setHandler(new RequestHandler(this))
                // 设置请求参数拦截器
                .setInterceptor(new IRequestInterceptor() {
                    @Override
                    public void interceptArguments(@NonNull HttpRequest<?> httpRequest,
                                                   @NonNull HttpParams params,
                                                   @NonNull HttpHeaders headers) {
                    }
                })
                // 设置请求重试次数
                .setRetryCount(1)
                // 设置请求重试时间
                .setRetryTime(2000)
                // 添加全局请求参数
//                .addParam("token", "6666666")
                // 添加全局请求头
//                .addHeader("secretKey", "")//密钥的前19位
                .addHeader(NET_CONSTANT.HEADER_CONTENT_TYPE_NAME, NET_CONSTANT.CONTENT_TYPE)//application/json 或者 application/json;charset=UTF-8
                .addHeader(NET_CONSTANT.HEADER_ISSECERT_NAME, NET_CONSTANT.IS_SECERT)//是否加密返回 1是 0否 ,值为1时接口
                .addHeader(NET_CONSTANT.HEADER_CODE_NAME, NET_CONSTANT.ITEM_CODE)//应用编码
                .into();
    }

    /**
     * 动态设置secretKey
     *
     * @param key
     * @param value
     */
    public void setEasyHttpHead(String key, String value) {
        EasyConfig.getInstance().setInterceptor(new IRequestInterceptor() {

            @Override
            public void interceptArguments(@NonNull HttpRequest<?> httpRequest, @NonNull HttpParams params, @NonNull HttpHeaders headers) {
                headers.put(key, value);
            }
        });
    }
} 